<template>
  <n-space vertical size="large">
    <!-- 统计信息 -->
    <n-card title="对比统计" :bordered="false">
      <n-grid :cols="24" :x-gap="16" :y-gap="16">
        <n-gi :span="isMobile ? 12 : 6">
          <n-statistic label="相同行">
            <n-number-animation
              :from="0"
              :to="result.summary.comparison.sameRows"
              :duration="1000"
            />
          </n-statistic>
        </n-gi>
        <n-gi :span="isMobile ? 12 : 6">
          <n-statistic label="修改行">
            <n-number-animation
              :from="0"
              :to="result.summary.comparison.modifiedRows"
              :duration="1000"
            />
          </n-statistic>
        </n-gi>
        <n-gi :span="isMobile ? 12 : 6">
          <n-statistic label="新增行">
            <n-number-animation
              :from="0"
              :to="result.summary.comparison.addedRows"
              :duration="1000"
            />
          </n-statistic>
        </n-gi>
        <n-gi :span="isMobile ? 12 : 6">
          <n-statistic label="删除行">
            <n-number-animation
              :from="0"
              :to="result.summary.comparison.deletedRows"
              :duration="1000"
            />
          </n-statistic>
        </n-gi>
      </n-grid>
      
      <n-divider />
      
      <n-descriptions :column="isMobile ? 1 : 2" label-placement="left">
        <n-descriptions-item label="表格1">
          {{ result.summary.table1.fileName }} 
          ({{ result.summary.table1.totalRows }}行 × {{ result.summary.table1.totalColumns }}列)
        </n-descriptions-item>
        <n-descriptions-item label="表格2">
          {{ result.summary.table2.fileName }}
          ({{ result.summary.table2.totalRows }}行 × {{ result.summary.table2.totalColumns }}列)
        </n-descriptions-item>
        <n-descriptions-item label="总差异数">
          {{ result.summary.comparison.totalDifferences }}
        </n-descriptions-item>
        <n-descriptions-item label="对比ID">
          {{ result.comparisonId }}
        </n-descriptions-item>
      </n-descriptions>
    </n-card>

    <!-- 详细对比结果 -->
    <n-card title="详细对比结果" :bordered="false">
      <template #header-extra>
        <n-space>
          <n-select
            v-model:value="filterStatus"
            :options="filterOptions"
            style="width: 150px"
            placeholder="筛选状态"
          />
          <n-button type="primary" @click="$emit('download')">
            <template #icon>
              <n-icon>
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor">
                  <path fill-rule="evenodd" d="M12 2.25a.75.75 0 01.75.75v11.69l3.22-3.22a.75.75 0 111.06 1.06l-4.5 4.5a.75.75 0 01-1.06 0l-4.5-4.5a.75.75 0 111.06-1.06l3.22 3.22V3a.75.75 0 01.75-.75zm-9 13.5a.75.75 0 01.75.75v2.25a1.5 1.5 0 001.5 1.5h13.5a1.5 1.5 0 001.5-1.5V16.5a.75.75 0 011.5 0v2.25a3 3 0 01-3 3H5.25a3 3 0 01-3-3V16.5a.75.75 0 01.75-.75z" clip-rule="evenodd" />
                </svg>
              </n-icon>
            </template>
            下载结果
          </n-button>
        </n-space>
      </template>

      <n-data-table
        :columns="columns"
        :data="filteredRows"
        :pagination="pagination"
        :scroll-x="scrollX"
        :loading="loading"
        :row-class-name="getRowClassName"
      />
    </n-card>
  </n-space>
</template>

<script setup lang="ts">
import { ref, computed, h } from 'vue'
import type { DataTableColumns } from 'naive-ui'
import { NTag, NBadge, NSpace, NText } from 'naive-ui'
import type { ComparisonResult, RowComparison } from '@/api/utility/tableComparison'
import { useBreakpoint } from '@/utils/responsive-helper'

interface Props {
  result: ComparisonResult
  loading?: boolean
}

const props = defineProps<Props>()
const emit = defineEmits<{
  download: []
}>()

const { isMobile } = useBreakpoint()

const filterStatus = ref<string>('ALL')
const filterOptions = [
  { label: '全部', value: 'ALL' },
  { label: '相同', value: 'SAME' },
  { label: '修改', value: 'MODIFIED' },
  { label: '新增', value: 'ADDED' },
  { label: '删除', value: 'DELETED' }
]

const pagination = ref({
  pageSize: isMobile.value ? 10 : 20,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100]
})

const filteredRows = computed(() => {
  if (filterStatus.value === 'ALL') {
    return props.result.details.rows
  }
  return props.result.details.rows.filter(row => row.status === filterStatus.value)
})

const scrollX = computed(() => {
  const columnCount = Math.max(
    props.result.details.columns.length,
    props.result.details.rows[0]?.table1Data?.length || 0,
    props.result.details.rows[0]?.table2Data?.length || 0
  )
  return Math.max(800, columnCount * 150)
})

const getStatusTag = (status: string) => {
  const config = {
    SAME: { type: 'default', text: '相同' },
    MODIFIED: { type: 'warning', text: '修改' },
    ADDED: { type: 'success', text: '新增' },
    DELETED: { type: 'error', text: '删除' }
  }[status] || { type: 'default', text: status }

  return h(NTag, { type: config.type as any }, { default: () => config.text })
}

const renderCell = (row: RowComparison, columnIndex: number, isTable2: boolean = false) => {
  const data = isTable2 ? row.table2Data : row.table1Data
  if (!data) return h(NText, { depth: 3 }, { default: () => '-' })
  
  const value = data[columnIndex] || ''
  const difference = row.differences?.find(d => d.columnIndex === columnIndex)
  
  if (difference && row.status === 'MODIFIED') {
    return h(
      NBadge,
      { dot: true, type: 'warning' },
      {
        default: () => h(
          NText,
          { type: 'warning', strong: true },
          { default: () => value }
        )
      }
    )
  }
  
  return value
}

const columns = computed<DataTableColumns<RowComparison>>(() => {
  const baseColumns: DataTableColumns<RowComparison> = [
    {
      title: '行号',
      key: 'rowNumber',
      width: 80,
      fixed: 'left'
    },
    {
      title: '状态',
      key: 'status',
      width: 100,
      fixed: 'left',
      render: (row) => getStatusTag(row.status)
    }
  ]

  // 动态生成列
  const dataColumns = props.result.details.columns.map((col, index) => ({
    title: () => h(
      NSpace,
      { vertical: true, size: 0 },
      {
        default: () => [
          h('div', `表1: ${col.table1Name || '-'}`),
          h('div', { style: 'color: var(--n-text-color3)' }, `表2: ${col.table2Name || '-'}`)
        ]
      }
    ),
    key: `col_${index}`,
    width: 150,
    render: (row: RowComparison) => h(
      NSpace,
      { vertical: true, size: 0 },
      {
        default: () => [
          h('div', renderCell(row, index, false)),
          h('div', { style: 'color: var(--n-text-color2)' }, renderCell(row, index, true))
        ]
      }
    )
  }))

  return [...baseColumns, ...dataColumns]
})

const getRowClassName = (row: RowComparison) => {
  return `row-status-${row.status.toLowerCase()}`
}
</script>

<style scoped>
:deep(.row-status-same) {
  background-color: var(--n-color);
}

:deep(.row-status-modified) {
  background-color: var(--n-warning-color-hover);
}

:deep(.row-status-added) {
  background-color: var(--n-success-color-hover);
}

:deep(.row-status-deleted) {
  background-color: var(--n-error-color-hover);
}
</style>